<script lang="ts" setup>
import { computed, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Button, Cascader, message, Space } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import {attrConfigAdd, attrConfigEdit, attrConfigUpdata, getOptions} from '#/api/attrConfig'
import { dictDataAdd, dictDataEdit } from '#/api/dict'
import { getCategoryTree } from '#/api/goodsCategory'

const emit = defineEmits(['refresh'])
const { SHOW_CHILD } = Cascader
const idsArr: any = ref([])
const inputDisabled = ref(true)
const categoryTree: any = ref([])
const Options: any = ref([])

const dict = ref(0)
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    { component: 'Input', fieldName: 'attr_name', label: '属性名称', rules: 'required' },
    { component: 'Input', fieldName: 'attr_key', label: '属性KEY' },
    {
      component: 'Select',
      defaultValue: ['2'],
      componentProps: {
        mode: 'multiple',
        options: [
          {
            label: '预生产计划',
            value: '1',
          },
          {
            label: '货品档案',
            value: '2',
          },
        ],
      },
      fieldName: 'use_area',
      label: '应用区域',
    },
    {
      component: 'RadioGroup',
      defaultValue: '0',
      componentProps: {
        options: [
          {
            label: '全部品类',
            value: '1',
          },
          {
            label: '指定品类',
            value: '0',
          },
        ],
      },
      fieldName: 'cate_tag',
      label: '品类范围',
    },
    {
      component: 'Cascader',
      fieldName: 'category_id',
      label: '指定品类',
      // 调整货品分类的宽度
      dependencies: {
        show(values) {
          return values.cate_tag === '0'
        },
        triggerFields: ['cate_tag'],
      },
      componentProps: {
        options: categoryTree,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
        multiple: true,
        showCheckedStrategy: SHOW_CHILD,
      },
    },
    {
      component: 'Cascader',
      fieldName: 'data_type',
      label: '数据类型',
      // 调整货品分类的宽度
      componentProps: {
        options: Options,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'attr.step',
      label: '步长',
      dependencies: {
        show(values) {

          return Array.isArray(values?.data_type) && values.data_type[0] === 'input-number';
        },
        triggerFields: ['data_type'],
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'attr.precision',
      label: '数字精度',
      dependencies: {
        show(values) {
          return Array.isArray(values?.data_type) && values.data_type[0] === 'input-number';
        },
        triggerFields: ['data_type'],
      },
    },
    { component: 'InputNumber', fieldName: 'sort', label: '权重' },
    {
      component: 'RadioGroup',
      defaultValue: '0',
      componentProps: {
        options: [
          {
            label: '否',
            value: '0',
          },
          {
            label: '是',
            value: '1',
          },
        ],
      },
      fieldName: 'attr.required_pull_erp',
      label: '推送ERP必填',
    },
  ],
  wrapperClass: 'grid-cols-1',
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[30%] h-[50%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      getCategoryTree().then((res) => {
        categoryTree.value = res
      })
      getOptions().then((res) => {
        Options.value = res.options
      })

      const { rowData, view, dict_id } = modalApi.getData<Record<string, any>>()
      dict.value = dict_id
      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})

async function initData(rowData: any) {
  attrConfigEdit({ id: rowData }).then(async (response) => {
    const row = response.row
    await baseFormApi.setValues(row, false)
  })
}
const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  const parmas = {
    ...values,
  }
  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      attrConfigUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.dict_id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      attrConfigUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    attrConfigAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}
</script>
<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm />
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped></style>
